package com.ruoyi.littleRedBook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.littleRedBook.domain.pojo.Favorite;
import com.ruoyi.littleRedBook.domain.pojo.Product;
import com.ruoyi.littleRedBook.mapper.FavoriteMapper;
import com.ruoyi.littleRedBook.mapper.ProductMapper;
import com.ruoyi.littleRedBook.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private ProductMapper productMapper;

    // 实际项目中从Token/Session获取当前登录用户ID，此处占位示例
    private Long getCurrentUserId() {
        return 1L; // 需替换为真实的当前用户ID获取逻辑
    }

    @Override
    public AjaxResult addFavorite(Long productId) {
        // 1. 校验商品是否存在且已上架
        Product product = productMapper.selectById(productId);
        if (product == null || product.getStatus() != 1) {
            return AjaxResult.error("商品不存在或未上架，无法收藏");
        }

        // 2. 校验是否已收藏（避免重复收藏，数据库有唯一约束，此处先校验提高用户体验）
        Long userId = getCurrentUserId();
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                    .eq("product_id", productId);
        Favorite existingFavorite = favoriteMapper.selectOne(queryWrapper);
        if (existingFavorite != null) {
            return AjaxResult.error("该商品已在您的收藏夹中");
        }

        // 3. 添加收藏
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        int rows = favoriteMapper.insert(favorite);
        if (rows > 0) {
            // 4. 商品收藏数+1
            product.setLikeCount(product.getLikeCount() + 1);
            productMapper.updateById(product);
            return AjaxResult.success("商品收藏成功");
        } else {
            return AjaxResult.error("商品收藏失败");
        }
    }

    @Override
    public AjaxResult removeFavorite(Long productId) {
        // 1. 校验收藏是否存在
        Long userId = getCurrentUserId();
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                    .eq("product_id", productId);
        Favorite favorite = favoriteMapper.selectOne(queryWrapper);
        if (favorite == null) {
            return AjaxResult.error("该商品不在您的收藏夹中");
        }

        // 2. 取消收藏
        int rows = favoriteMapper.deleteById(favorite.getId());
        if (rows > 0) {
            // 3. 商品收藏数-1
            Product product = productMapper.selectById(productId);
            if (product != null && product.getLikeCount() > 0) {
                product.setLikeCount(product.getLikeCount() - 1);
                productMapper.updateById(product);
            }
            return AjaxResult.success("商品取消收藏成功");
        } else {
            return AjaxResult.error("商品取消收藏失败");
        }
    }

    @Override
    public AjaxResult getMyFavoriteList(Integer pageNum, Integer pageSize) {
        Long userId = getCurrentUserId();
        Page<Favorite> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                    .orderByDesc("created_at"); // 按收藏时间倒序
        Page<Favorite> favoritePage = favoriteMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(favoritePage.getRecords());
    }

    @Override
    public AjaxResult checkFavorite(Long productId) {
        Long userId = getCurrentUserId();
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                    .eq("product_id", productId);
        Favorite favorite = favoriteMapper.selectOne(queryWrapper);
        return AjaxResult.success(favorite != null);
    }
}
